//
//  RBUploadTool.m
//  HuLin
//
//  Created by mac on 2022/10/25.
//

#import <UIKit/UIKit.h>
#import "RBUploadTool.h"
#import "RBRequestHM.h"
#import "RBURLConfig.h"
#import "RBUploadResponse.h"
#import "RanTool.h"
#import "RBAppDelegateHelper.h"
#import "UIView+RBAdd.h"

@implementation RBUploadModel

@end

@interface RBUploadTool()

@property(nonatomic, strong) RBRequestHM *hm;
@property(nonatomic, strong) NSArray *data;
@property(nonatomic, copy) void(^completion)(NSArray *data);
@property(nonatomic, assign) BOOL waterMark;

@end

@implementation RBUploadTool

- (void)uploadData:(NSArray *)data withCompletion:(void (^)(NSArray *))completion
{
    self.data = data;
    self.completion = completion;
    [self startUpload];
}

- (void)uploadWaterMarkData:(NSArray *)data withCompletion:(void (^)(NSArray *))completion
{
    self.waterMark = YES;
    self.data = data;
    self.completion = completion;
    [self startUpload];
}

- (void)startUpload
{
    __weak typeof(self) weak_self = self;
    for(NSInteger i = 0; i < self.data.count; i++)
    {
        RBUploadModel *model = self.data[i];
        if(!model.res.length)
        {
            if([model.source isKindOfClass:UIImage.class])
            {
                [self.hm requestWithParam:^(NSMutableDictionary *dicM) {
                    
                } log:YES post:YES cancelLastRequest:NO fileParam:({
                    NSMutableDictionary *dicM = NSMutableDictionary.dictionary;
                    dicM[kRBRequestMime] = @[@"image/jpeg"];
                    dicM[kRBRequestName] = @[@"picurl"];
                    dicM[kRBRequestFileName] = @[@"1.jpg"];
                    dicM[kRBRequestData] = @[[RanTool dataFromImage:model.source]];
                    dicM;
                }) fileProgress:nil responseClass:RBUploadResponse.class pathName:@"han_imgup" completion:^(RBUploadResponse *response) {
                    if(response.succeed)
                    {
                        model.res = response.data;
                        [weak_self startUpload];
                    }
                    else
                    {
                        [RBAppDelegateHelper.keyWindow showTip:@"图片上传失败" completion:nil];
                    }
                }];
                return;
            }
            else
            {
                NSString *source = model.source;
                model.res = [source stringByReplacingOccurrencesOfString:RBURLConfig.shareInstance.commonServicePicUrl withString:@""];
                [self startUpload];
                return;
            }
        }
    }
    if(self.completion)
    {
        self.completion(self.data);
    }
}

#pragma mark - Getter

- (RBRequestHM *)hm
{
    if(!_hm)
    {
        self.hm = RBRequestHM.new;
    }
    return _hm;
}

@end
